import chartOp from '@/common/chart-option.js';
// import { convertData as scatterConvertData } from '@/components/scatter/chart-option.js';
import { clone, numFormat, xssFilter } from '@/utils/util';
import optionList from './chart-option.json';
import colorBoard from './color_board';
import defaultOption from './config/defaultOption.js';

const tooltip = {
  backgroundColor: '',
  dataLength: '',
  seriesNameColor: '',
  componentStyle: '',
};
const chartOption = null;

/**
 * 根据数据量来设置图表dataZoom
 * @param {*} option 图表option
 * @param {*} data 图表数据
 * @param {*} property 配置页面中属性面板中的参数
 */
function setDataZoom(option, data, property) {
  chartOp.setDataZoom('common-x-multiple-y', { option, data, property, colorBoard });
  if (option.dataZoom[0]) {
    option.dataZoom[0].start = 0;
    delete option.dataZoom[0].startValue;
  }
}

/**
 * 设置图表数据 series legend等
 * @param {*} option 图表option
 * @param {*} data 图表数据
 * @param {*} property 配置页面中属性面板中的参数
 */
function setChartData(option, data, property) {
  const { xAxisData, seriesData } = data;
  const { componentStyle, legend, color } = property;
  option.xAxis.data = xAxisData;
  const colors = colorBoard[componentStyle].colorGroup[color];
  let serie;
  let realIndex = 0;
  seriesData.forEach((item, index) => {
    if (item.isBlank) {
      serie = {
        type: 'bar', name: item.name, data: item.data, stack: item.stack,
        itemStyle: { barBorderColor: 'rgba(0,0,0,0)', color: 'rgba(0,0,0,0)' },
        emphasis: { itemStyle: { barBorderColor: 'rgba(0,0,0,0)', color: 'rgba(0,0,0,0)' } },
      };
    } else {
      if (item.type === 'bar') {
        serie = { type: 'bar', name: item.name, data: item.data, stack: item.stack };
        if (Array.isArray(colors[realIndex])) {
          serie.itemStyle = {
            color: {
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: colors[index][0] },
                { offset: 1, color: colors[index][1] },
              ],
            },
          };
        } else {
          serie.itemStyle = { color: colors[realIndex] };
        }
      } else {
        serie = {
          type: 'line', name: item.name, data: item.data, stack: item.stack, symbol: 'circle',
          symbolSize: 6, smooth: true,
        };
        if (Array.isArray(colors[realIndex])) {
          serie.itemStyle = { color: colors[realIndex][0] };
        } else {
          serie.itemStyle = { color: colors[realIndex] };
        }
      }
      realIndex++;
    }

    if (item.name) {
      option.legend.data.push(item.name);
    }
    option.series.push(serie);
  });
}

function formateTooltip(params) {
  if (!chartOp.isOrgTooltipVisible()) {
    return '';
  }
  const { seriesNameColor } = tooltip;
  let formatStr = '<div class=\'tooltip_bar\'>';
  params.forEach((item, i) => {
    xssFilter(item, ['axisValue', 'seriesName', 'value']);
    if (i === 0) {
      formatStr += `<span>${item.axisValue}</span><br/>`;
    }
    if (i === 0 || i === 2) {
      return;
    }
    if (item.color && item.color.colorStops) {
      const { color } = item.color.colorStops[0];
      if (item.seriesName) {
        formatStr +=
          '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;' +
          `background-color:${color};'></span><span style='color:${seriesNameColor}'> ${
            item.seriesName
          }:</span> ${numFormat(item.value, true)}`;
      } else {
        formatStr +=
          '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;' +
          `background-color:${color};'></span><span style='color:${seriesNameColor}'> </span> ${numFormat(
            item.value,
            true,
          )}`;
      }
    } else {
      if (item.seriesName) {
        formatStr += `${item.marker}<span style='color:${seriesNameColor}'>${item.seriesName}:</span> ${numFormat(
          item.value,
          true,
        )}`;
      } else {
        formatStr += `${item.marker}<span style='color:${seriesNameColor}'></span> ${numFormat(item.value, true)}`;
      }
    }
    if (i !== params.length) {
      formatStr += '<br/>';
    }
  });
  formatStr += '<div/>';
  return formatStr;
}


/**
 * 将接口数据转换为echart方便使用的数据
 * @param {*} data 接口数据
 */
export const convertData = function({ data, xAxisKey, seriesKey, chartType }) {

  if (data.length) {
    const seriesData = [];
    const newData = data;

    /*
     * 塞入数据
     * 有分组的情况
     */
    if (seriesKey.length) {
      seriesKey.forEach(s => {
        xAxisKey.forEach(x => {
          const item = seriesData.find(sData => sData.name === s);
          const data1 = newData.find(d => d.x === x && d.s === s);
          const y = (data1 && data1.y) || 0;
          if (item) {
            item.data.push([x, y]);
          } else {
            seriesData.push({
              name: s,
              data: [[x, y]],
            });
          }
        });
      });
    } else {
      xAxisKey.forEach(x => {
        const item = seriesData.find(sData => sData.name === '');
        const data1 = newData.find(d => d.x === x);
        const y = (data1 && data1.y) || 0;
        if (item) {
          item.data.push([x, y]);
        } else {
          seriesData.push({
            name: '',
            data: [[x, y]],
          });
        }
      });
    }

    return {
      xAxisData: xAxisKey,
      seriesData,
    };
  } else {
    return null;
  }
};

// 整理出和其他图表格式一致的property

export const getChartProperty = function(property, index) {
  const {
    barNum,
    barShow,
    componentStyle,
    xAxisName,
    xLabelRotate,
    padding,
    data,
    yAxisNameLeft,
    chartPadding = 30,
  } = property;
  const { chartType, yAxisName, option } = data[index];
  const { barWidth, arrangement, color, legend, lineType, shadow, isMarklineShow, hasMarkLine, markLine } = option;

  const dataProperty = {
    ...defaultOption[chartType],
    barNum,
    barShow,
    xAxisName,
    xLabelRotate,
    padding,
    chartPadding,
    yAxisNameLeft,
    chartType,
    yAxisName,
    barWidth,
    arrangement,
    color,
    legend,
    lineType,
    shadow,
    isMarklineShow,
    hasMarkLine,
    markLine,
    useForCommonX: true, // 标记用于x轴公用
    ...option, // 补充其他属性
    componentStyle, // 防止被option覆盖
  };

  return JSON.parse(JSON.stringify(dataProperty));
};

export const getXAxisKeyAndSeriesKey = function(data) {
  const seriesKey = [];
  const xAxisKey = [];
  for (let i = 0; i < data.length; i++) {
    const { x } = data[i];
    const { s } = data[i];
    const isIncludeX = xAxisKey.includes(x);
    if (!isIncludeX) {
      xAxisKey.push(x);
    }
    if (s) {
      const isIncludeS = seriesKey.includes(s);
      if (!isIncludeS) {
        seriesKey.push(s);
      }
    }
  }
  return { seriesKey, xAxisKey };
};

export const setChartOption = (data, property, configData) => {
  const { xAxisName = '', componentStyle, barWidth, tooltip: { originTooltipSetting } = {} } = property;
  tooltip.backgroundColor =
    (originTooltipSetting && originTooltipSetting.background) || colorBoard[componentStyle].tooltip.backgroundColor;
  tooltip.dataLength = data.xAxisData.length;
  tooltip.componentStyle = componentStyle;
  tooltip.seriesNameColor = colorBoard[componentStyle].tooltip.seriesNameColor;

  const vars = {
    componentStyle,
    colorBoard,
    barWidth,
    xAxisName,
    xLabelRotate: property.xLabelRotate || 0,
    tooltipBgColor: tooltip.backgroundColor,
    formateTooltip,
  };
  let option = clone(optionList);
  option = chartOp.parseJsonOption(option, vars);

  setDataZoom(option, data, property);
  setChartData(option, data, property);
  chartOp.setYAxisName('common-x-multiple-y', { option, property, colorBoard });

  // 附加公共配置
  option = chartOp.mergeOption(option, property);

  return option;
};
